﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    public class QuestionCard : ListBoxItem
    {
        public QuestionCard(Question question)
        {
            this.FontFamily = new FontFamily("Simsun");
            this.FontSize = 14;
            this.Focusable = false;
            this.VerticalContentAlignment = VerticalAlignment.Stretch;

            this.PreviewMouseLeftButtonDown += QuestionCard_PreviewMouseLeftButtonDown;

            if (question == null)
            {
                this.Content = new TextBlock() { Text = "不明内容试题！", };
                return;
            }

            var trimChars = new char[] { ' ', '　', '\r', '\n', '\t', };
            this.Style = this.FindResource("MetroListBoxItem") as Style;
            this.masterQuestion = question;
            var baseBorder = new Border()
            {
                BorderBrush = Brushes.SaddleBrown,
                BorderThickness = new System.Windows.Thickness(1),
                Margin = new Thickness(2, 4, 8, 4),
                Padding = new System.Windows.Thickness(2),
            };
            this.Content = baseBorder;

            TextOptions.SetTextRenderingMode(this, TextRenderingMode.Aliased);
            TextOptions.SetTextFormattingMode(this, TextFormattingMode.Display);

            var baseDockPanel = new DockPanel() { LastChildFill = true, };
            baseBorder.Child = baseDockPanel;

            baseDockPanel.Children.Add(this.ckx);
            DockPanel.SetDock(this.ckx, Dock.Right);

            var spQuestion = new StackPanel() { Orientation = Orientation.Vertical, };
            var scrollViewer = new ScrollViewer();
            scrollViewer.Content = spQuestion;
            baseDockPanel.Children.Add(scrollViewer);

            switch (question.Type)
            {
                case QuestionType.Choice:
                case QuestionType.Judge:
                    {
                        var tbTitle = new TextBlock()
                        {
                            Text = question.OrderNumber + "．" + question.TitleString.Trim(trimChars),
                            TextWrapping = TextWrapping.Wrap,
                        };
                        spQuestion.Children.Add(tbTitle);

                        qTextBlocks.Add(tbTitle);

                        if (string.IsNullOrWhiteSpace(question.MarkdownImageLinkRealPath) == false &&
                            System.IO.File.Exists(question.MarkdownImageLinkRealPath))
                        {
                            var bmp = Globals.LoadBitmapImageFromFile(question.MarkdownImageLinkRealPath);
                            var img = new Image()
                            {
                                HorizontalAlignment = HorizontalAlignment.Center,
                                MaxHeight = 100,
                                Source = bmp,
                                Width = bmp.Width,
                            };
                            spQuestion.Children.Add(img);
                        }

                        foreach (var ci in question.ChoiceItems)
                        {
                            var tb = new TextBlock()
                            {
                                Text = " " + (ci.IsAnswer ? "★ " : "○ ") + ci.Text.Trim(trimChars),
                                TextWrapping = TextWrapping.Wrap,
                                FontWeight = FontWeights.Bold,
                            };

                            spQuestion.Children.Add(tb);
                            qTextBlocks.Add(tb);

                            var anaTextBlock = new TextBlock()
                            {
                                Text = "　　解析：" + ci.AnalysisText.Trim(trimChars),
                                TextWrapping = TextWrapping.Wrap,
                                Visibility = Visibility.Collapsed,
                            };
                            spQuestion.Children.Add(anaTextBlock);
                            anaTextBlocks.Add(anaTextBlock);

                            tb.Foreground = ci.IsAnswer ? Brushes.Red : Brushes.Green;
                            anaTextBlock.Foreground = Brushes.DarkBlue;
                        }
                        break;
                    }
                case QuestionType.FillBlank:
                    {
                        var tbTitle = new TextBlock()
                        {
                            Text = question.OrderNumber + "．" + question.TitleString.Trim(trimChars),
                            TextWrapping = TextWrapping.Wrap,
                        };
                        spQuestion.Children.Add(tbTitle);

                        qTextBlocks.Add(tbTitle);

                        if (string.IsNullOrWhiteSpace(question.MarkdownImageLinkRealPath) == false &&
                            System.IO.File.Exists(question.MarkdownImageLinkRealPath))
                        {
                            var bmp = Globals.LoadBitmapImageFromFile(question.MarkdownImageLinkRealPath);
                            var img = new Image()
                            {
                                Width = bmp.Width,
                                HorizontalAlignment = HorizontalAlignment.Center,
                                MaxHeight = 100,
                                Source = bmp,
                            };
                            spQuestion.Children.Add(img);
                        }

                        var tbAnswer = new TextBlock()
                        {
                            Text = "　　答：" + question.Answer.Trim(trimChars),
                            TextWrapping = TextWrapping.Wrap,
                            Visibility = Visibility.Collapsed,
                        };
                        anaTextBlocks.Add(tbAnswer);
                        spQuestion.Children.Add(tbAnswer);
                        break;
                    }
                case QuestionType.Subjective:
                    {
                        var title = this.MasterQuestion.TitleString.Trim();
                        if (string.IsNullOrWhiteSpace(title))
                        {
                            title = "阅读下列材料：";
                        }
                        else
                        {
                            title = title.TrimStart(new char[] { '.', '．' });
                        }
                        var tbTitle = new TextBlock()
                        {
                            Text = question.OrderNumber + "．" + title,
                            TextWrapping = TextWrapping.Wrap,
                        };
                        spQuestion.Children.Add(tbTitle);
                        qTextBlocks.Add(tbTitle);

                        foreach (var m in question.Materials)
                        {
                            if (m.StartsWith("＜＜材料＞＞"))
                            {
                                var subm = m.Substring(6).Trim(new char[] { '\r', '\n' });
                                if (string.IsNullOrWhiteSpace(subm)) continue;
                            }

                            var index = m.IndexOf("＜＜出处＞＞");
                            if (index < 0)
                            {
                                var tbcl = new TextBlock()
                                {
                                    Text = "　" + m.Substring(6).Trim(trimChars).Replace("\r\n", "\r\n　　"),
                                    TextWrapping = TextWrapping.Wrap,
                                };
                                spQuestion.Children.Add(tbcl);
                                qTextBlocks.Add(tbcl);
                            }
                            else
                            {
                                var cl = m.Substring(6, index);
                                var tbcl = new TextBlock()
                                {
                                    Text = "　" + cl.Trim(trimChars).Replace("\r\n", "\r\n　　"),
                                    TextWrapping = TextWrapping.Wrap,
                                };
                                spQuestion.Children.Add(tbcl);
                                qTextBlocks.Add(tbcl);
                                var cc = m.Substring(index + 6);
                                var tbcc = new TextBlock()
                                {
                                    Text = "——" + cc.Trim(trimChars),
                                    TextWrapping = TextWrapping.Wrap,
                                    TextAlignment = System.Windows.TextAlignment.Right,
                                };
                                spQuestion.Children.Add(tbcc);
                                qTextBlocks.Add(tbcc);
                            }
                        }

                        var tbTip = new TextBlock() { Text = "请回答：" };
                        spQuestion.Children.Add(tbTip);
                        qTextBlocks.Add(tbTip);

                        if (question.Answers.Count == question.AsksList.Count)
                        {
                            for (int j = 0; j < question.Answers.Count; j++)
                            {
                                var tbAsk = new TextBlock()
                                {
                                    Text = $"　({j + 1})" + question.AsksList[j].Trim(trimChars),
                                    TextWrapping = TextWrapping.Wrap,
                                    Foreground = Brushes.Green,
                                    FontWeight = FontWeights.Bold,
                                };
                                spQuestion.Children.Add(tbAsk);
                                qTextBlocks.Add(tbAsk);

                                var tbAnswer = new TextBlock()
                                {
                                    Text = "　　答：" + question.Answers[j].Trim(trimChars),
                                    TextWrapping = TextWrapping.Wrap,
                                    Foreground = Brushes.DarkBlue,
                                    Visibility = Visibility.Collapsed,
                                };
                                spQuestion.Children.Add(tbAnswer);
                                qTextBlocks.Add(tbAnswer);
                            }
                        }
                        break;
                    }
                default:
                    this.Content = new TextBlock() { Text = "不明类型试题！", };
                    return;
            }
        }

        public void ShowAnswerOrAnalisys()
        {
            foreach (var tb in anaTextBlocks)
            {
                tb.Visibility = Visibility.Visible;
            }
        }

        public void HideAnswerOrAnalisys()
        {
            foreach (var tb in anaTextBlocks)
            {
                tb.Visibility = Visibility.Collapsed;
            }
        }

        private void QuestionCard_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            this.IsSelected = true;
            if (this.IsChecked == true)
            {
                this.IsChecked = false;
            }
            else this.IsChecked = true;
            e.Handled = true;
        }

        private CheckBox ckx = new CheckBox()
        {
            IsChecked = true,
            HorizontalAlignment = HorizontalAlignment.Center,
        };

        public bool? IsChecked
        {
            get { return this.ckx.IsChecked; }
            set
            {
                this.ckx.IsChecked = value;
            }
        }

        private Question masterQuestion;
        public Question MasterQuestion { get { return masterQuestion; } }

        public List<TextBlock> qTextBlocks = new List<TextBlock>();

        public List<TextBlock> anaTextBlocks = new List<TextBlock>();
    }

    public class QuestionCardIgnoredEventArgs : EventArgs
    {
        public Question Question { get; set; }
    }
}
